// 自动根据menu.txt 生成 后端 router 包含后续给到后端的json文件和前端模拟的js文件
const fs = require('fs');
let path = require('path');
const data = fs.readFileSync(__dirname + '/menu.txt', 'utf8');
const arr = data.split('\r\n');

let activeIndex = 0; // 当前父级的id
const menuPath = [];
const nameArr = [];

const icons = ['videodevice', 'sorDevice', 'devicegroup'];

function titleCase(str) {
    return (
        str.replace('-', '').slice(0, 1).toUpperCase() + str.slice(1).toLowerCase()
    );
}
function nameCase(str) {
    return str.replace('-', '').slice(0, 1).toUpperCase() + str.slice(1);
}
function getIcon(arr) {
    const [title, name] = arr;
    if (title.includes('视频设备')) {
        return icons[0];
    } else if (title.includes('传感器设备')) {
        return icons[1];
    } else if (title.includes('分组管理')) {
        return icons[2];
    } else {
        return name.toLowerCase();
    }
}

let subIndex = 0;

const getRouter = (name, index, isTop = 1) => {
    const nameArr = name.split('|');
    let component = nameArr[2] || '#';
    let redirect = nameArr[3] || undefined;
    console.log(nameArr);
    if (!nameArr || nameArr.length === 0) return;
    const path = nameArr[1].toLowerCase();

    const icon = getIcon(nameArr);
    const obj = {
        id: index + '',
        name: nameCase(nameArr[1]),
        type: 2,
        title:  nameArr[0].replace(/-/g, ''),
        icon:`svg:${icon}`,
        parentId: '',
        component,
        redirect,
        path: path,
        isChecked: 0,
        sortNumber: index,
    };
    if (obj.name === 'Home') {
        obj.affix = true
    }

    if (isTop == 2) {
        obj.parentId = activeIndex + '';
    } else if (isTop == 3) {
        obj.parentId = subIndex + '';
    }
    return obj;
};

arr.forEach((item, index) => {
    if (!item) return;

    if (/^--/.test(item)) {
        const activeIndex = menuPath;
        const router = getRouter(item, index + 1, 3);
        menuPath.push(router);
    } else if (/^-/.test(item)) {
        const router = getRouter(item, index + 1, 2);
        menuPath.push(router);
        subIndex = index + 1;
    } else {
        const router = getRouter(item, index + 1);
        menuPath.push(router);
        activeIndex = index + 1;
    }

    if (/^-/.test(item)) {
        nameArr.push(item.split('|')[0].replace(/-/g, ''));
    }
});

const str = JSON.stringify(menuPath, '', '\t');
const objstr = 'export const menuArr=' + str;

fs.writeFile(__dirname + '/menu.ts', objstr, function (err) {
    if (err) {
        return console.log('文件写入失败！' + err.message);
    }
    console.log('文件写入成功！');
});

fs.writeFile(__dirname + '/menu.json', str, function (err) {
    if (err) {
        return console.log('文件写入失败！' + err.message);
    }
    console.log('文件写入成功！');
});

const strnameArr = JSON.stringify(nameArr, '', '\t');

fs.writeFile(__dirname + '/name.json', strnameArr, function (err) {
    if (err) {
        return console.log('文件写入失败！' + err.message);
    }
    console.log('文件写入成功！');
});
